#include "driver/rmt.h"
#include "encoder_rmt.h"

static void rmt_task(void *arg)
{
    encoder_rmt_t * prmt = (encoder_rmt_t *)arg;
    rmt_item32_t* items = NULL;
    size_t length = 0;
    while(1) 
    {
        items = xRingbufferReceive(prmt->ringbuf, &length, portMAX_DELAY);
        if (items) 
        {
            prmt->recvcb((int8_t*)items,length,prmt->axis);
            vRingbufferReturnItem(prmt->ringbuf, items);
        }
    }
}

void encoder_rmt_init(rmt_channel_t channel,gpio_num_t pin,uint8_t clk_div,
                        uint8_t filter,uint16_t idle,RmtReceiveFunc_t recvfunc,uint8_t axis)
{
    encoder_rmt_t * prmt = (encoder_rmt_t*)malloc(sizeof(encoder_rmt_t));
    rmt_config_t rmt_rx = {
        .channel = channel,
        .gpio_num = pin,
        /*
         * 当 clk_div=1 时：时钟频率 = 80MHz / 1 = 80MHz（12.5ns 分辨率）
         * 当 clk_div=80 时：时钟频率 = 80MHz / 80 = 1MHz（1μs 分辨率）
         */
        .clk_div = clk_div,  // 80 MHz / 80 = 1 MHz (1μs 分辨率) 
        .mem_block_num = 1,
        .rmt_mode = RMT_MODE_RX,
        .rx_config.filter_en = true,
        .rx_config.filter_ticks_thresh = filter,  // 实际时间(秒) = filter_ticks_thresh × (clk_div / 80,000,000)
        .rx_config.idle_threshold = idle      // 实际时间(秒) = idle_threshold × (clk_div / 80,000,000) 
    };
    prmt->channel = channel;
    prmt->pin = pin;
    prmt->recvcb = recvfunc;
    prmt->axis = axis;
    rmt_config(&rmt_rx);
    rmt_driver_install(channel, RINGBUF_LENGTH, 0);
    
    // 启动接收
    rmt_get_ringbuf_handle(channel, &prmt->ringbuf);
    rmt_rx_start(channel, true);
    
    // 在任务中处理接收到的信号
    xTaskCreate(rmt_task, "rmt_task", 4096, prmt, 10, NULL);    
}
